package com.sun.impls.users;

import cn.dev33.satoken.util.SaResult;
import com.sun.dto.users.MenuSearchDto;
import com.sun.entity.users.Menu;
import com.sun.impls.BaseService;
import com.sun.repository.users.MenuRepository;
import com.sun.services.CustomPredicate;
import com.sun.services.users.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * MP自动填充Handler
 *
 * @Author sun
 * @CreateTime 2025/9/4 20:16
 */
@Service
public class MenuServiceImpl extends BaseService implements MenuService {

    @Autowired
    private MenuRepository menuRepository;

    @Override
    public SaResult createMenu(Menu menu) {
        menu.setId(nextId());
        menuRepository.save(menu);
        return SaResult.ok("菜单创建成功");
    }

    @Override
    public SaResult updateMenu(Menu menu) {
        Menu oldMenu = menuRepository.findById(menu.getId()).filter(m -> m.getDeleted() == 0).orElse(null);
        if (oldMenu == null) {
            return SaResult.error("菜单不存在");
        }
        menuRepository.save(menu);

        return SaResult.ok("菜单更新成功");
    }

    @Override
    public SaResult deleteMenu(List<Long> ids) {
        menuRepository.deleteAllById(ids);
        return SaResult.ok("菜单删除成功");
    }

    @Override
    public SaResult getMenuList(MenuSearchDto search) {
        CustomPredicate<Menu> predicate = (cb, root) -> basePredicates(cb, root, search);
        return SaResult.data(getList(Menu.class, predicate, search));
    }
}
